<template>
    <div class="create-post-page">
    <h4>{{isEditMode?'编辑文章':'新建文章'}}</h4>
     <uploader
      action="/upload"
      :beforeUpload="uploadCheck"
      @file-uploaded="handleFileUploaded"
      :uploaded="uploadedData"
      class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
    >
    
      <h2>点击上传头图</h2>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary" role="status">
            <span class="sr-only">Loading...</span>
          </div>
          <h2>正在上传</h2>
        </div>
      </template>
      <template #uploaded="dataProps">
        <div class="uploaded-area">
          <img :src="dataProps.uploadedData.data.url">
          <h3>点击重新上传</h3>
        </div>
      </template>
    </uploader>
    <h2>{{titleVal}}</h2>
    <validate-form @form-submit="onFormSubmit">
      <!-- 上传组件 -->
      <input type="file" name="file" @change="handleFileChange"/>
      <div class="mb-3">
        <label class="form-label">文章标题：</label>
        <validate-input
          :rules="titleRules" v-model="titleVal"
          placeholder="请输入文章标题"
          type="text"
        />
      </div>
      <div class="mb-3">
        <label class="form-label">文章详情：</label>
        <validate-input
          rows="10"
          tag="textarea"
          placeholder="请输入文章详情"
          :rules="contentRules"
          v-model="contentVal"
        />
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">{{isEditMode?'发表文章':'发表文章'}}</button>
      </template>
    </validate-form>
  </div>
</template>
<script lang="ts">
import {defineComponent,onMounted,ref} from 'vue'
import {GlobalDataProps,PostProps,ResponseType,ImageProps} from '../store'
import {useStore} from 'vuex'
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
import ValidateForm from '../components/ValidateForm.vue'
import { useRouter,useRoute} from 'vue-router'
import axios from 'axios'
import {beforeUploadCheck} from '../helper'
import createMessage from '../components/createMessage'
export default defineComponent({
    name:'CreatePost',
    components:{
        ValidateInput,
        ValidateForm
    },
    setup(){
        const uploadedData = ref()
        const store=useStore<GlobalDataProps>()
        const router=useRouter()
        const route = useRoute()
        const titleVal = ref('')
        const contentVal = ref('')
        let imageId=''
        const isEditMode = !!route.query.id
        const titleRules: RulesProp = [
            { type: 'required', message: '文章标题不能为空' }
        ]
        const contentRules: RulesProp = [
            { type: 'required', message: '文章详情不能为空' }
        ]
        const handleFileUploaded = (rawData: ResponseType<ImageProps>) => {
          if (rawData.data.id) {
            imageId = rawData.data.id
          }
        }
        const onFormSubmit=(result:boolean)=>{
            if(result){
                const {columnId}=store.state.user
                if(columnId){
                    const newPost:PostProps={
                        id:new Date().getTime(),
                        title:titleVal.value,
                        content:contentVal.value,
                        columnId,
                        createdAt:new Date().toLocaleString()
                    }
                    if (imageId) {
                      newPost.image = imageId
                    }
                    const actionName = isEditMode ? 'updatePost' : 'createPost'
                    const sendData = isEditMode ? {
                      id: route.query.id,
                      payload: newPost
                    } : newPost
                    store.dispatch(actionName, sendData).then(() => {
                      createMessage('发表成功，2秒后跳转到文章', 'success', 2000)
                      setTimeout(() => {
                        router.push({ path: `/column/${columnId}`})
                      }, 2000)
                    })
                }
            }
        }
        onMounted(() => {
          if (isEditMode) {
            store.dispatch('fetchPost', route.query.id).then((rawData: ResponseType<PostProps>) => {
              const currentPost = rawData.data
              if (currentPost.image) {
                uploadedData.value = { data: currentPost.image }
              }
              titleVal.value = currentPost.title
              contentVal.value = currentPost.content || ''
            })
          }
        })

        // 上传文件
        const handleFileChange=(e:Event)=>{
          const target=e.target as HTMLInputElement
          const files=target.files
          if(files){
            const uploadedFile=files[0]
            const formData=new FormData()
            formData.append(uploadedFile.name,uploadedFile)
            axios.post('/upload',formData,{
              headers:{
                'Content-Type':'multipart/form-data'
              }
            }).then((resp:any)=>{
              console.log(resp)
            })
          }
        }
        const uploadCheck=(file:File)=>{
          const result=beforeUploadCheck(file,{format:['image/jpeg','image/png'],size:1})
          const {passed,error}=result
          if(error==='format'){
            createMessage('上传图片只能是JPG/PNG格式！','error')
          }
          if(error==='size'){
            createMessage('上传图片大小不能超过1MB','error')
          }
          return passed
        }
        return{
            titleRules,
            contentRules,
            titleVal,
            contentVal,
            uploadedData,
            isEditMode,
            onFormSubmit,
            uploadCheck,
            handleFileUploaded
        }
    }
})
</script>
<style scoped>
/* .create-post-page{
    width: 500px;
    margin: 0 auto;
    margin-top: 30px;
} */
.create-post-page .file-upload-container {
  height: 200px;
  cursor: pointer;
  overflow: hidden;
}
.create-post-page .file-upload-container img {
  width: 100%;
  height: 100%;
  /* 图片样式宽高自适应 */
  object-fit: cover;  
}
.uploaded-area {
  position: relative;
}
.uploaded-area:hover h3 {
  display: block;
}
.uploaded-area h3 {
  display: none;
  position: absolute;
  color: #999;
  text-align: center;
  width: 100%;
  top: 50%;
}
</style>